<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
</head>
<body>

<form onsubmit="return false;">

    <textarea name="message" style="height:400px;width:400px;"> </textarea>
    <input type="button" value="发送数据" onclick="send(this.form.message.value)">

    <h3>服务端输出：</h3>
    <textarea name="responseText" style="height:400px;width:400px;"> </textarea>
    <input type="button" value="清空数据" onclick="javascript:document.getElementsByName('responseText').value=''">

</form>
<script type="text/javascript">
    var socket;
    if (window.WebSocket) {
        var ta = document.getElementsByName("responseText")[0];
        socket = new WebSocket("ws://localhost:8899/ws");
        socket.onmessage=function (event) {

            ta.value=ta.value + '\n' + event.data;
        };
        socket.onopen=function () {
            console.info('链接开启！')
            ta.value ='链接开启！';
        };
        socket.onclose=function () {
            ta.value ='链接断开！'
        };
    } else {
        alert("浏览器不支持webSocket")
    }

    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message)
        } else {
            alert("连接未开启")
        }

    }
</script>
</body>
</html>